package com.doublethread.easymart.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doublethread.easymart.common.exception.FileException;
import com.doublethread.easymart.common.exception.ProductException;
import com.doublethread.easymart.common.result.PageResult;
import com.doublethread.easymart.common.utils.Base64MultipartFile;
import com.doublethread.easymart.common.utils.OssUtils;
import com.doublethread.easymart.modules.cart.entity.Cart;
import com.doublethread.easymart.modules.cart.mapper.CartMapper;
import com.doublethread.easymart.modules.order.entity.OrderItem;
import com.doublethread.easymart.modules.order.mapper.OrderItemMapper;
import com.doublethread.easymart.modules.product.dto.ProductDTO;
import com.doublethread.easymart.modules.product.dto.ProductQueryDTO;
import com.doublethread.easymart.modules.product.dto.ProductUpdateStatusDTO;
import com.doublethread.easymart.modules.product.dto.ProductUpdateStockDTO;
import com.doublethread.easymart.modules.product.entity.Category;
import com.doublethread.easymart.modules.product.entity.Product;
import com.doublethread.easymart.modules.product.mapper.CategoryMapper;
import com.doublethread.easymart.modules.product.mapper.ProductMapper;
import com.doublethread.easymart.modules.product.service.ProductService;
import com.doublethread.easymart.modules.product.vo.ProductStatisticsVO;
import com.doublethread.easymart.modules.product.vo.ProductVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 商品服务实现类
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public PageResult<ProductVO> getProductList(ProductQueryDTO queryDTO) {
        log.info("获取商品列表: keyword={}, categoryId={}, brand={}, minPrice={}, maxPrice={}, current={}, size={}",
                queryDTO.getKeyword(), queryDTO.getCategoryId(), queryDTO.getBrand(),
                queryDTO.getMinPrice(), queryDTO.getMaxPrice(), queryDTO.getCurrent(), queryDTO.getSize());

        // 构建查询条件
        LambdaQueryWrapper<Product> queryWrapper = buildQueryWrapper(queryDTO);

        // 公开接口只显示上架的商品
        queryWrapper.eq(Product::getStatus, 1);

        // 是否只显示有库存商品
        if (queryDTO.getInStock() != null && queryDTO.getInStock()) {
            queryWrapper.gt(Product::getStock, 0);
        }

        // 分页查询
        Page<Product> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<Product> productPage = this.page(page, queryWrapper);

        // 使用PageResult.of方法进行转换
        return PageResult.of(productPage, this::convertToProductVO);
    }

    @Override
    public ProductVO getProductById(Long productId) {
        log.info("获取商品详情");

        Product product = this.getById(productId);
        if (product == null || product.getStatus() == 0) {
            ProductException.productNotFound();
        }

        return convertToProductVO(product);
    }

    @Override
    public PageResult<ProductVO> searchProducts(ProductQueryDTO queryDTO) {
        log.info("搜索商品");

        // 搜索功能复用getProductList
        return getProductList(queryDTO);
    }

    @Override
    public List<ProductVO> getHotProducts(Integer limit) {
        log.info("获取热门商品: limit={}", limit);

        List<Product> products = this.list(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1)
                .gt(Product::getStock, 0)
                .orderByDesc(Product::getSales)
                .last("LIMIT " + (limit != null ? limit : 10)));

        return products.stream()
                .map(this::convertToProductVO)
                .toList();
    }

    @Override
    public List<ProductVO> getNewProducts(Integer limit) {
        log.info("获取新品推荐");

        List<Product> products = this.list(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1)
                .gt(Product::getStock, 0)
                .orderByDesc(Product::getCreateTime)
                .last("LIMIT " + (limit != null ? limit : 10)));

        return products.stream()
                .map(this::convertToProductVO)
                .toList();
    }

    @Override
    public List<ProductVO> getRelatedProducts(Long productId, Integer limit) {
        log.info("获取相关商品");

        // 获取当前商品信息
        Product currentProduct = this.getById(productId);
        if (currentProduct == null) {
            return new ArrayList<>();
        }

        // 查找同分类的其他商品
        List<Product> products = this.list(new LambdaQueryWrapper<Product>()
                .eq(Product::getCategoryId, currentProduct.getCategoryId())
                .eq(Product::getStatus, 1)
                .gt(Product::getStock, 0)
                .ne(Product::getId, productId)
                .orderByDesc(Product::getSales)
                .last("LIMIT " + (limit != null ? limit : 10)));

        return products.stream()
                .map(this::convertToProductVO)
                .toList();
    }

    @Override
    public List<String> getBrands() {
        log.info("获取品牌列表");

        // 查询所有不为空的品牌，去重
        List<Product> products = this.list(new LambdaQueryWrapper<Product>()
                .select(Product::getBrand)
                .isNotNull(Product::getBrand)
                .ne(Product::getBrand, "")
                .eq(Product::getStatus, 1)
                .groupBy(Product::getBrand));

        return products.stream()
                .map(Product::getBrand)
                .distinct()
                .toList();
    }

    // ==================== 管理端接口实现 ====================

    @Override
    public PageResult<ProductVO> getAdminProductList(ProductQueryDTO queryDTO) {
        log.info("管理端查询商品列表");

        // 构建查询条件
        LambdaQueryWrapper<Product> queryWrapper = buildQueryWrapper(queryDTO);

        // 状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Product::getStatus, queryDTO.getStatus());
        }

        // 是否只显示低库存商品
        if (queryDTO.getLowStock() != null && queryDTO.getLowStock()) {
            queryWrapper.le(Product::getStock, 10); // 库存小于等于10认为是低库存
        }

        // 分页查询
        Page<Product> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<Product> productPage = this.page(page, queryWrapper);

        // 使用PageResult.of方法进行转换
        return PageResult.of(productPage, this::convertToProductVO);
    }

    @Override
    public ProductVO getAdminProductById(Long productId) {
        log.info("管理端获取商品详情");

        Product product = this.getById(productId);
        if (product == null) {
            ProductException.productNotFound();
        }

        return convertToProductVO(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductVO createProduct(ProductDTO productDTO) {
        log.info("创建商品");

        // 检查分类是否存在
        Category category = categoryMapper.selectById(productDTO.getCategoryId());
        if (category == null || category.getStatus() == 0) {
            ProductException.categoryNotFound();
        }

        // 检查商品名称是否已存在
        checkProductNameExists(productDTO.getName(), null);

        // 处理主图上传
        String finalMainImage = productDTO.getMainImage();
        if (finalMainImage != null && finalMainImage.startsWith("data:image/")) {
            log.info("上传主图");
            try {
                finalMainImage = uploadProductImage(finalMainImage);
                log.info("主图上传成功");
            } catch (Exception e) {
                log.error("主图上传失败");
                FileException.uploadFailed();
            }
        }

        // 处理子图上传
        List<String> finalSubImages = new ArrayList<>();
        if (productDTO.getSubImages() != null && !productDTO.getSubImages().isEmpty()) {
            for (String subImage : productDTO.getSubImages()) {
                if (subImage != null && subImage.startsWith("data:image/")) {
                    log.info("检测到Base64子图数据，开始上传到OSS");
                    try {
                        String uploadedUrl = uploadProductImage(subImage);
                        finalSubImages.add(uploadedUrl);
                        log.info("子图上传成功: url={}", uploadedUrl);
                    } catch (Exception e) {
                        log.error("子图上传失败: error={}", e.getMessage());
                        // 子图上传失败不影响商品创建，跳过该图片
                    }
                } else if (subImage != null && subImage.startsWith("http")) {
                    // URL格式，直接使用
                    finalSubImages.add(subImage);
                }
            }
        }

        // 构建商品实体
        Product product = Product.builder()
                .name(productDTO.getName())
                .subtitle(productDTO.getSubtitle())
                .mainImage(finalMainImage)
                .subImages(convertSubImagesToJson(finalSubImages))
                .detail(productDTO.getDetail())
                .price(productDTO.getPrice())
                .originalPrice(productDTO.getOriginalPrice())
                .stock(productDTO.getStock())
                .sales(0) // 初始销量为0
                .categoryId(productDTO.getCategoryId())
                .brand(productDTO.getBrand())
                .weight(productDTO.getWeight())
                .unit(productDTO.getUnit() != null ? productDTO.getUnit() : "件")
                .keywords(productDTO.getKeywords())
                .status(1) // 默认上架
                .build();

        // 保存商品
        this.save(product);

        log.info("商品创建成功");
        return convertToProductVO(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(Long productId, ProductDTO productDTO) {
        log.info("更新商品");

        // 检查商品是否存在
        Product existingProduct = this.getById(productId);
        if (existingProduct == null) {
            ProductException.productNotFound();
        }

        // 检查分类是否存在
        Category category = categoryMapper.selectById(productDTO.getCategoryId());
        if (category == null || category.getStatus() == 0) {
            ProductException.categoryNotFound();
        }

        // 检查商品名称是否已存在（排除当前商品）
        checkProductNameExists(productDTO.getName(), productId);

        // 处理主图上传
        String finalMainImage = productDTO.getMainImage();
        String oldMainImage = existingProduct.getMainImage();
        if (finalMainImage != null && finalMainImage.startsWith("data:image/")) {
            log.info("上传主图");
            try {
                finalMainImage = uploadProductImage(finalMainImage);
                log.info("主图上传成功");

                // 异步删除旧主图
                if (oldMainImage != null && !oldMainImage.isEmpty() && oldMainImage.startsWith("http")) {
                    CompletableFuture.runAsync(() -> {
                        try {
                            ossUtils.deleteImage(oldMainImage);
                            log.info("删除旧主图成功");
                        } catch (Exception e) {
                            log.warn("删除旧主图失败");
                        }
                    });
                }
            } catch (Exception e) {
                log.error("主图上传失败");
                FileException.uploadFailed();
            }
        }

        // 处理子图上传
        List<String> finalSubImages = new ArrayList<>();
        if (productDTO.getSubImages() != null && !productDTO.getSubImages().isEmpty()) {
            for (String subImage : productDTO.getSubImages()) {
                if (subImage != null && subImage.startsWith("data:image/")) {
                    log.info("检测到Base64子图数据，开始上传到OSS");
                    try {
                        String uploadedUrl = uploadProductImage(subImage);
                        finalSubImages.add(uploadedUrl);
                        log.info("子图上传成功: url={}", uploadedUrl);
                    } catch (Exception e) {
                        log.error("子图上传失败: error={}", e.getMessage());
                        // 子图上传失败不影响商品更新，跳过该图片
                    }
                } else if (subImage != null && subImage.startsWith("http")) {
                    // URL格式，直接使用
                    finalSubImages.add(subImage);
                }
            }
        }

        // 构建更新实体
        Product updateProduct = Product.builder()
                .id(productId)
                .name(productDTO.getName())
                .subtitle(productDTO.getSubtitle())
                .mainImage(finalMainImage)
                .subImages(convertSubImagesToJson(finalSubImages))
                .detail(productDTO.getDetail())
                .price(productDTO.getPrice())
                .originalPrice(productDTO.getOriginalPrice())
                .stock(productDTO.getStock())
                .categoryId(productDTO.getCategoryId())
                .brand(productDTO.getBrand())
                .weight(productDTO.getWeight())
                .unit(productDTO.getUnit() != null ? productDTO.getUnit() : "件")
                .keywords(productDTO.getKeywords())
                .build();

        // 更新商品
        this.updateById(updateProduct);

        // 同步更新订单项和购物车中的冗余数据
        syncRelatedData(productId, productDTO.getName(), finalMainImage, productDTO.getPrice());

        log.info("商品更新成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Long productId) {
        log.info("删除商品");

        // 检查商品是否存在
        Product product = this.getById(productId);
        if (product == null) {
            ProductException.productNotFound();
        }

        // 使用MyBatis-Plus软删除
        this.removeById(productId);

        log.info("商品删除成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductStatus(Long productId, ProductUpdateStatusDTO statusDTO) {
        log.info("更新商品状态: productId={}, status={}", productId, statusDTO.getStatus());

        // 检查商品是否存在
        Product product = this.getById(productId);
        if (product == null) {
            ProductException.productNotFound();
        }

        // 更新状态
        Product updateProduct = new Product();
        updateProduct.setId(productId);
        updateProduct.setStatus(statusDTO.getStatus());
        this.updateById(updateProduct);

        log.info("商品状态更新成功: productId={}, status={}", productId, statusDTO.getStatus());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductStock(Long productId, ProductUpdateStockDTO stockDTO) {
        log.info("更新商品库存");

        // 检查商品是否存在
        Product product = this.getById(productId);
        if (product == null) {
            ProductException.productNotFound();
        }

        // 更新库存
        Product updateProduct = new Product();
        updateProduct.setId(productId);
        updateProduct.setStock(stockDTO.getStock());
        this.updateById(updateProduct);

        log.info("商品库存更新成功");
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Product> buildQueryWrapper(ProductQueryDTO queryDTO) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();

        // 关键词搜索
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Product::getName, queryDTO.getKeyword())
                    .or().like(Product::getSubtitle, queryDTO.getKeyword())
                    .or().like(Product::getBrand, queryDTO.getKeyword())
                    .or().like(Product::getKeywords, queryDTO.getKeyword()));
        }

        // 分类筛选 - 支持包含子分类
        if (queryDTO.getCategoryId() != null) {
            if (Boolean.TRUE.equals(queryDTO.getIncludeSubCategories())) {
                // 获取该分类及其所有子分类的ID
                List<Long> categoryIds = getCategoryIdsWithChildren(queryDTO.getCategoryId());
                if (!categoryIds.isEmpty()) {
                    queryWrapper.in(Product::getCategoryId, categoryIds);
                }
            } else {
                // 精确匹配单个分类
                queryWrapper.eq(Product::getCategoryId, queryDTO.getCategoryId());
            }
        }

        // 品牌筛选
        if (StringUtils.hasText(queryDTO.getBrand())) {
            queryWrapper.eq(Product::getBrand, queryDTO.getBrand());
        }

        // 价格区间筛选
        if (queryDTO.getMinPrice() != null) {
            queryWrapper.ge(Product::getPrice, queryDTO.getMinPrice());
        }
        if (queryDTO.getMaxPrice() != null) {
            queryWrapper.le(Product::getPrice, queryDTO.getMaxPrice());
        }

        // 排序处理
        if ("price".equals(queryDTO.getSortBy())) {
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Product::getPrice);
            } else {
                queryWrapper.orderByAsc(Product::getPrice);
            }
        } else if ("sales".equals(queryDTO.getSortBy())) {
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Product::getSales);
            } else {
                queryWrapper.orderByAsc(Product::getSales);
            }
        } else if ("stock".equals(queryDTO.getSortBy())) {
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Product::getStock);
            } else {
                queryWrapper.orderByAsc(Product::getStock);
            }
        } else {
            // 默认按创建时间排序
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Product::getCreateTime);
            } else {
                queryWrapper.orderByAsc(Product::getCreateTime);
            }
        }

        return queryWrapper;
    }

    /**
     * 获取指定分类及其所有子分类的ID列表
     */
    private List<Long> getCategoryIdsWithChildren(Long categoryId) {
        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);  // 包含自身

        // 查询子分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, categoryId)
                .eq(Category::getStatus, 1);  // 只查询启用的分类

        List<Category> subCategories = categoryMapper.selectList(queryWrapper);
        for (Category subCategory : subCategories) {
            categoryIds.add(subCategory.getId());
        }

        log.debug("分类ID {} 包含子分类: {}", categoryId, categoryIds);
        return categoryIds;
    }

    /**
     * 检查商品名称是否已存在
     */
    private void checkProductNameExists(String name, Long excludeId) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<Product>()
                .eq(Product::getName, name);

        // 排除当前商品
        if (excludeId != null) {
            queryWrapper.ne(Product::getId, excludeId);
        }

        long count = this.count(queryWrapper);
        if (count > 0) {
            ProductException.productNameExists();
        }
    }

    /**
     * 转换子图列表为JSON字符串
     */
    private String convertSubImagesToJson(List<String> subImages) {
        if (subImages == null || subImages.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(subImages);
        } catch (JsonProcessingException e) {
            log.error("转换子图列表为JSON失败", e);
            return null;
        }
    }

    /**
     * 转换JSON字符串为子图列表
     */
    private List<String> convertJsonToSubImages(String subImagesJson) {
        if (!StringUtils.hasText(subImagesJson)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(subImagesJson, new TypeReference<List<String>>() {
            });
        } catch (JsonProcessingException e) {
            log.error("转换JSON为子图列表失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 转换Product实体为ProductVO
     */
    private ProductVO convertToProductVO(Product product) {
        // 获取分类名称
        String categoryName = null;
        if (product.getCategoryId() != null) {
            Category category = categoryMapper.selectById(product.getCategoryId());
            if (category != null) {
                categoryName = category.getName();
            }
        }

        return ProductVO.builder()
                .id(product.getId())
                .name(product.getName())
                .subtitle(product.getSubtitle())
                .mainImage(product.getMainImage())
                .subImages(convertJsonToSubImages(product.getSubImages()))
                .detail(product.getDetail())
                .price(product.getPrice())
                .originalPrice(product.getOriginalPrice())
                .stock(product.getStock())
                .sales(product.getSales())
                .categoryId(product.getCategoryId())
                .categoryName(categoryName)
                .brand(product.getBrand())
                .weight(product.getWeight())
                .unit(product.getUnit())
                .keywords(product.getKeywords())
                .status(product.getStatus())
                .createTime(product.getCreateTime())
                .updateTime(product.getUpdateTime())
                .build();
    }

    @Override
    public String uploadProductImage(String imageBase64) {
        // 商品图片上传路径常量
        final String PRODUCT_IMAGE_PATH = "images/product/";

        try {
            log.info("开始上传商品图片");

            // 1. 验证Base64数据格式
            if (imageBase64 == null || !imageBase64.startsWith("data:image/")) {
                log.error("商品图片数据格式不正确");
                FileException.typeNotAllowed();
            }

            // 2. 将Base64数据转换为MultipartFile
            MultipartFile imageFile = Base64MultipartFile.fromBase64(imageBase64);

            // 3. 验证图片文件大小（限制5MB）
            if (imageFile.getSize() > 5 * 1024 * 1024) {
                log.error("商品图片文件过大: size={} bytes", imageFile.getSize());
                FileException.sizeExceeded();
            }

            // 4. 使用OSS工具上传图片到指定路径
            String imageUrl = ossUtils.uploadImage(imageFile, PRODUCT_IMAGE_PATH);

            // 5. 验证上传结果
            if (imageUrl == null || imageUrl.isEmpty()) {
                log.error("OSS上传返回空URL");
                FileException.uploadFailed();
            }

            log.info("商品图片上传成功: imageUrl={}", imageUrl);
            return imageUrl;

        } catch (Exception e) {
            log.error("商品图片上传失败: error={}", e.getMessage(), e);
            // 重新抛出异常，不返回null
            if (e instanceof RuntimeException) {
                throw e;
            }
            FileException.uploadFailed();
            return null; // 这行不会执行，因为上面会抛异常
        }
    }

    /**
     * 同步更新相关表中的商品冗余数据
     */
    private void syncRelatedData(Long productId, String productName, String productImage, BigDecimal price) {
        try {
            log.debug("同步商品相关数据");

            // 同步订单项中的商品信息
            LambdaUpdateWrapper<OrderItem> orderItemWrapper = new LambdaUpdateWrapper<OrderItem>()
                    .eq(OrderItem::getProductId, productId)
                    .eq(OrderItem::getStatus, 1)
                    .eq(OrderItem::getIsDeleted, 0)
                    .set(OrderItem::getProductName, productName)
                    .set(OrderItem::getProductImage, productImage)
                    .set(OrderItem::getUnitPrice, price);

            int orderItemCount = orderItemMapper.update(null, orderItemWrapper);

            // 同步购物车中的商品价格
            LambdaUpdateWrapper<Cart> cartWrapper = new LambdaUpdateWrapper<Cart>()
                    .eq(Cart::getProductId, productId)
                    .set(Cart::getPrice, price);

            int cartCount = cartMapper.update(null, cartWrapper);

            if (orderItemCount > 0 || cartCount > 0) {
                log.info("商品数据同步完成");
            }
        } catch (Exception e) {
            log.error("同步商品相关数据失败");
            // 不抛异常，避免影响商品更新的主流程
        }
    }

    @Override
    public ProductStatisticsVO getProductStatistics() {
        log.info("获取商品统计信息");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        LocalDate today = now.toLocalDate();
        LocalDate weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1);
        LocalDate monthStart = today.withDayOfMonth(1);

        // ==================== 基础统计 ====================

        // 商品总数
        Long totalProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0));

        // 在售商品数
        Long activeProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .eq(Product::getStatus, 1));

        // 下架商品数
        Long inactiveProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .eq(Product::getStatus, 0));

        // ==================== 新增统计 ====================

        // 今日新增商品数
        Long todayNewProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .ge(Product::getCreateTime, today.atStartOfDay())
                .lt(Product::getCreateTime, today.plusDays(1).atStartOfDay()));

        // 本周新增商品数
        Long weekNewProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .ge(Product::getCreateTime, weekStart.atStartOfDay())
                .lt(Product::getCreateTime, today.plusDays(1).atStartOfDay()));

        // 本月新增商品数
        Long monthNewProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .ge(Product::getCreateTime, monthStart.atStartOfDay())
                .lt(Product::getCreateTime, today.plusDays(1).atStartOfDay()));

        // ==================== 库存统计 ====================

        // 库存不足商品数（库存 <= 10）
        Long lowStockProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .eq(Product::getStatus, 1)
                .le(Product::getStock, 10)
                .gt(Product::getStock, 0));

        // 零库存商品数
        Long outOfStockProducts = this.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .eq(Product::getStatus, 1)
                .eq(Product::getStock, 0));

        // ==================== 价格和销量统计 ====================

        // 查询所有商品进行统计计算
        List<Product> allProducts = this.list(new LambdaQueryWrapper<Product>()
                .eq(Product::getIsDeleted, 0)
                .eq(Product::getStatus, 1));

        BigDecimal avgPrice = BigDecimal.ZERO;
        BigDecimal maxPrice = BigDecimal.ZERO;
        BigDecimal minPrice = BigDecimal.ZERO;
        Long totalStock = 0L;
        Long totalSales = 0L;

        if (!allProducts.isEmpty()) {
            // 计算平均价格
            BigDecimal totalPrice = allProducts.stream()
                    .map(Product::getPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            avgPrice = totalPrice.divide(BigDecimal.valueOf(allProducts.size()), 2, RoundingMode.HALF_UP);

            // 计算最高和最低价格
            maxPrice = allProducts.stream()
                    .map(Product::getPrice)
                    .max(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);

            minPrice = allProducts.stream()
                    .map(Product::getPrice)
                    .min(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);

            // 计算总库存和总销量
            totalStock = allProducts.stream()
                    .mapToLong(Product::getStock)
                    .sum();

            totalSales = allProducts.stream()
                    .mapToLong(Product::getSales)
                    .sum();
        }

        // ==================== 分类和品牌统计 ====================

        // 分类总数
        Long totalCategories = categoryMapper.selectCount(new LambdaQueryWrapper<Category>()
                .eq(Category::getIsDeleted, 0)
                .eq(Category::getStatus, 1));

        // 品牌总数（去重）
        List<String> brands = this.getBrands();
        Long totalBrands = (long) brands.size();

        // 构建统计结果
        return ProductStatisticsVO.builder()
                .totalProducts(totalProducts)
                .activeProducts(activeProducts)
                .inactiveProducts(inactiveProducts)
                .todayNewProducts(todayNewProducts)
                .weekNewProducts(weekNewProducts)
                .monthNewProducts(monthNewProducts)
                .lowStockProducts(lowStockProducts)
                .outOfStockProducts(outOfStockProducts)
                .avgPrice(avgPrice)
                .maxPrice(maxPrice)
                .minPrice(minPrice)
                .totalStock(totalStock)
                .totalSales(totalSales)
                .totalCategories(totalCategories)
                .totalBrands(totalBrands)
                .statisticsTime(now)
                .build();
    }
}
